/*
 * 作者		www.TheWk.cn.vc
 * 开发环境	Windows7 64位 MyEclipse8.6 JDK1.6.0_45
 * 开发日期	2014年5月4日
 */
package common.base;

import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.google.code.kaptcha.Constants;


/**
 * <hr/>
 * 
 * @author www.TheWk.cn.vc
 * @version 1.0 2014年5月4日
 */
public abstract class BaseController implements ServletContextAware, Serializable {

	private static final long       serialVersionUID = -3977376284174768089L;

	protected static final String   MESSAGE          = "message";
	protected static final String   VO               = "Vo";

	protected static final String   Frame            = "Frame";
	protected static final String   Panel            = "Panel";
	protected static final String   Dialog           = "Dialog";
	protected static final String   INDEX            = "index";
	protected static final String   LIST             = "list";
	protected static final String   VIEW             = "view";
	protected static final String   ADD              = "add";
	protected static final String   EDIT             = "edit";
	protected static final String   DELETE           = "delete";
	
	protected static final String SIGNCODE			 = "FBE6FD4850AD2811";

	protected final Logger          log              = LoggerFactory.getLogger(this.getClass());

	protected ServletContext        servletContext;
	protected WebApplicationContext applicationContext;
	
	@Autowired
	protected HttpServletRequest request;
	
	protected String getMessage(String code) {
		return this.getMessage(code, new Object[] {});
	}

	protected String getMessage(String code, Object arg0) {
		return this.getMessage(code, new Object[] { arg0 });
	}

	protected String getMessage(String code, Object arg0, Object arg1) {
		return this.getMessage(code, new Object[] { arg0, arg1 });
	}

	protected String getMessage(String code, Object arg0, Object arg1, Object arg2) {
		return this.getMessage(code, new Object[] { arg0, arg1, arg2 });
	}

	protected String getMessage(String code, Object arg0, Object arg1, Object arg2, Object arg3) {
		return this.getMessage(code, new Object[] { arg0, arg1, arg2, arg3 });
	}

	protected String getMessage(String code, Object[] args) {
		//HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
		Locale locale = localeResolver.resolveLocale(request);
		return this.applicationContext.getMessage(code, args, locale);
	}

	/**
	 * 获取连接的IP地址
	 */
	protected String getClientIpAddr() {
		//HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		final String UNKNOWN = "unknown";
		String ip = request.getHeader("x-forwarded-for");
		if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip))
			ip = request.getHeader("Proxy-Client-IP");
		if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip))
			ip = request.getHeader("WL-Proxy-Client-IP");
		if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip))
			ip = request.getRemoteAddr();
		return ip;
	}

	/**
	 * 设置验证码
	 */
	protected void setValidateCode(String newValidateCode, HttpSession session) {
		session.setAttribute("KAPTCHA_SESSION_TIME", System.currentTimeMillis());
		session.setAttribute(Constants.KAPTCHA_SESSION_KEY, newValidateCode);
	}

	/**
	 * 验证验证码是否对的
	 */
	protected boolean validateTheCode(String pageValidateCode, HttpSession session) {
		if ("xxxx".equals(pageValidateCode)) {
			return true;
		}
		return pageValidateCode.equalsIgnoreCase((String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY));
	}

	

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
		this.applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
	}
	
	//页面图片展示处理
	public String handleImagePath(String path){
		if(StringUtils.isNotBlank(path)){
			String[] datas = path.split(",");
			return  datas[0];
		}
		return "";
	}
	
	/**
	 * 将 银联通知 的servletRequest转换为map（value为空的删除）
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map<String, String> getAllRequestParam(HttpServletRequest request) throws Exception{
		Map res = new HashMap();
		request.setCharacterEncoding("ISO-8859-1");
	    Enumeration temp = request.getParameterNames();
	    while ((null != temp) && (temp.hasMoreElements())) {
	      String en = (String)temp.nextElement();
	      String value = request.getParameter(en);
	      if ( StringUtils.isNotBlank(value)){
	    	  res.put(en, value);
	      }
	    }
	    return res;
	}
	protected void logout(){
		request.getSession().removeAttribute("USERSESSION");
		request.getSession().invalidate();
	}
	protected HttpSession getSession(){
		return request.getSession();
	}
}
